package scalab.tasks.archives

import scalab.core.component.Component

/**
* Common class to all archivers.
*/
trait Archive extends scalab.core.component.Task{

	import scala.collection.immutable.{Map, HashMap}
	import java.io.File
	import scalab.core.gates.Input

	private var pairedInputs: Map[Input, Input] = HashMap.empty[Input, Input]
	def coupledInputs: Map[Input, Input] = pairedInputs

	val destinationArchive: String

	protected def hasOutOfDate: Boolean = pairedInputs.keys exists {i =>
		!i.outOfDateSources.isEmpty	
	}
	

	def execute(destinationDir: String): Boolean = {
		import java.io.File
		if(hasOutOfDate){ //an archive is always recreated entirely (no file replacement...)!
			val destinationPath = destinationDir + destinationArchive
			val succeeded = makeArchive(destinationPath)
			if(succeeded){
				built(destinationPath)
			}
			succeeded
		}
		else
			true
	}

	protected def makeArchive(destinationDir: String): Boolean

	def coupledInput: (Input, Input) = {
		val pair = (mandatoryIn, mandatoryIn)
		pairedInputs = coupledInputs + pair
		pair
	}

	def archiveInput(component: Component): Input = {
		val pair = coupledInput
		component.productDirectories -> pair._2
		pair._1
	}

	def instanceId: String = destinationArchive
}
